﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebSocketClientApp
{
    public class WebSocketClient
    {
        private const string Uri = "ws://localhost:8080/";
        private ClientWebSocket _ws;

        public async Task ConnectAsync()
        {
            try
            {
                _ws = new ClientWebSocket();
                await _ws.ConnectAsync(new Uri(Uri), CancellationToken.None);
                Console.WriteLine("WebSocket 客户端已连接");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public async Task SendMessageAsync(string message)
        {
            try
            {
                if (_ws != null && _ws.State == WebSocketState.Open)
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(message);
                    await _ws.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
                    Console.WriteLine("发送消息：" + message);
                }
                else
                {
                    Console.WriteLine("无法发送消息：WebSocket 客户端未连接或状态不正确");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public async Task ReceiveMessageAsync()
        {
            try
            {
                if (_ws != null && _ws.State == WebSocketState.Open)
                {
                    byte[] buffer = new byte[1024];
                    var result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                    Console.WriteLine($"收到消息：{Encoding.UTF8.GetString(buffer, 0, result.Count)}");
                }
                else
                {
                    Console.WriteLine("无法接收消息：WebSocket 客户端未连接或状态不正确");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public async Task DisconnectAsync()
        {
            try
            {
                if (_ws != null && _ws.State == WebSocketState.Open)
                {
                    await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                    Console.WriteLine("WebSocket 客户端已断开连接");
                }
                _ws?.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
